﻿// // ******************************************************************
// //       /\ /|       @file       ExceptionMiddleware.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-10 15:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-03 07:11 Await
// // ******************************************************************

using System.Text.Json;

namespace AutomaticSubtitles.Service.Infrastructure.Middlewares;

public class ExceptionMiddleware : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try
        {
            if (context.Request.Path == "/") context.Request.Path = "/index.html";

            await next(context);

            if (context.Response.StatusCode == 404)
            {
                var webHost = context.RequestServices.GetRequiredService<IWebHostEnvironment>();
                if (File.Exists(Path.Combine(webHost.WebRootPath, "index.html")))
                {
                    await using var file = File.OpenRead(Path.Combine(webHost.WebRootPath, "index.html"));
                    await file.CopyToAsync(context.Response.Body);
                }
            }
        }
        catch (UnauthorizedAccessException)
        {
            context.Response.StatusCode = ErroLose;
        }
        catch (UserFriendlyException e)
        {
            context.Response.StatusCode = Success;
            await context.Response.Body.WriteAsync(
                JsonSerializer.SerializeToUtf8Bytes(
                    e.CreateExceptionResult(ErroOk),
                    new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    }));
        }
        catch (Exception e) when (e is ArgumentNullException or ArgumentException or InvalidOperationException or ArgumentOutOfRangeException)
        {
            context.Response.StatusCode = Success;
            await context.Response.Body.WriteAsync(
                JsonSerializer.SerializeToUtf8Bytes(e.CreateExceptionResult(ErroOk),
                    new JsonSerializerOptions()
                    {
                        PropertyNameCaseInsensitive = true,
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    }));
        }
        catch (Exception e)
        {
            context.Response.StatusCode = Success;
            await context.Response.Body.WriteAsync(
                JsonSerializer.SerializeToUtf8Bytes(e.CreateExceptionResult(Erro),
                    new JsonSerializerOptions()
                    {
                        PropertyNameCaseInsensitive = true,
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    }));
        }
    }
}